<template>
  <a-modal
    :title="formTile + '账号'"
    :visible="true"
    width="70%"
    :footer="null"
    @cancel="reset"
  >
    <div class="main">
      <a-card v-if="showTable">
        <a-row style="margin-bottom: 10px">
          <a-col :span="24">
            <a-form
              layout="inline"
              :form="form"
              @submit="handleSubmit"
            >
              <a-form-item label="姓名">
                <a-input
                  allow-clear
                  placeholder="请输入姓名"
                  v-decorator="['name']"
                ></a-input>
              </a-form-item>
              <a-form-item label="工号">
                <a-input
                  allow-clear
                  placeholder="请输入工号"
                  v-decorator="['jobNumber']"
                ></a-input>
              </a-form-item>
              <a-form-item>
                <a-button
                  type="primary"
                  html-type="submit"
                >搜索</a-button>
              </a-form-item>
            </a-form>
          </a-col>
        </a-row>
        <a-table
          bordered
          :row-selection="{ selectedRowKeys: selectedRowKeys,selectedRows:selectedRows, onChange: onSelectChange ,type:'radio'}"
          :columns="columns"
          :loading="loading"
          :data-source="dataList"
        />

      </a-card>
      <a-card>
        <a-row style="margin-bottom: 10px">
          <a-col :span="24">
            <a-form
              layout="inline"
              :form="form"
              @submit="handleSubmit"
            >
              <a-form-item label="角色名称">
                <a-input
                  allow-clear
                  placeholder="请输入角色名称"
                  v-decorator="['name']"
                ></a-input>
              </a-form-item>
              <a-form-item>
                <a-button
                  type="primary"
                  html-type="submit"
                >搜索</a-button>
              </a-form-item>
            </a-form>
          </a-col>
        </a-row>
        <a-table
          bordered
          :row-selection="rowSelection"
          :columns="role"
          :loading="loadingRole"
          :data-source="roleList"
          :row-key="record => record.id"
        />

      </a-card>
      <a-card style="margin-top:5px">

        <a-form
          layout="inline"
          :form="form"
          @submit="beforeSubmit"
        >
          <a-row>
            <!-- <a-form-item label="品牌"> -->
             <span style="position: relative;top: -17px;"> 品牌：</span>
              <a-checkbox-group
                v-model="brand"
                style="width:90%"
                @change="selectBrand"
              >
                <a-row>
                  <a-col
                    :span="4"
                    v-for="item in brandList"
                    :key="item"
                  >
                    <a-checkbox :value="item">
                      {{ item }}
                    </a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
            <!-- </a-form-item> -->
          </a-row>
          <a-row>
            <!-- <a-form-item label="权限"> -->
              <span style="    position: relative;
    top: -5px;"> 权限：</span>
              <a-checkbox-group
                style="width: 90%;"
                v-model="permiss"
                @change="selectPermiss"
              >
                <a-row style="margin-top: 10px;">
                  <a-col
                    :span="4"
                    v-for="item in permission"
                    :key="item"
                  >
                    <a-checkbox :value="item">
                      {{ item }}
                    </a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
            <!-- </a-form-item> -->
          </a-row>
          <a-row>
            <a-col
              :span="24"
              :style="{ textAlign: 'right' }"
            >
              <a-button @click="reset">
                取消
              </a-button>
              <a-button
                :style="{ marginLeft: '8px' }"
                type="primary"
                html-type="submit"
              >
                保存
              </a-button>

            </a-col>

          </a-row>

        </a-form>

      </a-card>
    </div>

  </a-modal>
</template>

<script>
import { postAction } from '@/api/manage'
import { pattern } from '@api/pattern/index'
const columns = [
  {
    title: '姓名',
    dataIndex: 'name',
  },
  {
    title: '账号',
    dataIndex: 'email',
  },
  {
    title: '工号',
    dataIndex: 'jobNumber',
  },
  {
    title: '手机号',
    dataIndex: 'mobile',
  },
]
const role = [
  {
    title: '角色id',
    dataIndex: 'id',
  },
  {
    title: '角色名称',
    dataIndex: 'name',
  },
]
const permission = ['主推', '选款', '删款']
const brandList = ['JNBY', 'CROQUIS', '童装', '婴童', 'LESS', '蓬马', 'APN 73', 'JNBY HOME','校服']
export default {
  components: {},

  props: {
    account: {
      type: Object,
      default: null,
    },
  },

  data() {
    return {
      urlKey: 'account',
      patt: 'api/gateway/basemgt-op/',
      columns,
      role,
      permission,
      checkRole: [],
      loading: true,
      loadingRole: true,
      permiss: [],
      brand: [],
      accountInfo: [],
      form: this.$form.createForm(this),
      dataList: [],
      selectedRowKeys: [],
      selectedRows: [],
      selectedKey: [],
      selectedRow: [],
      roleList: [],
      brandList,
      ifChange: false,
      showTable: false,
      chooseStyle: '',
      deleteStyle: '',
      mainDesigner: '',
      defaultCheckedId: [],
    }
  },

  computed: {
    rowSelection() {
      return {
        //表格默认选中
        type: 'radio',
        onChange: (selectedRowKeys, selectedRows) => {
          selectedRows.forEach((item) => {
            this.defaultCheckedId.push(item.id) //在默认选中的基础上，做了另外选择（如果没写，则会出现的问题：除了选中id为1，2，3，的数据，选择不上其他数据）
          })
          this.ifChange = true
          this.selectedKey = selectedRowKeys
          this.selectedRow = selectedRows
          console.log(this.selectedRow)
        },
        getCheckboxProps: (record) => ({
          //重点部分
          props: {
            defaultChecked: this.defaultCheckedId.indexOf(record.id) > -1 ? true : false, //defaultCheckedId里面是默认选中的id，判断是否含有这些id，有的那就选中，没有的就不选中
            id: record.id + '', //使得id的数据类型为string
          },
        }),
      }
    },
  },

  created() {
    const { account } = this.$props
    this.brand = account.brand
    this.accountInfo = account
    if (account.mainDesigner == 1) {
      this.permiss.push('主推')
    }
    if (account.chooseStyle == 1) {
      this.permiss.push('选款')
    }
    if (account.deleteStyle == 1) {
      this.permiss.push('删款')
    }
    if (account) {
      this.formTile = '编辑'
    } else {
      this.formTile = '新增'
      this.showTable = true
    }
  },
  mounted() {
    this.loadData()
    this.getRoleList()
    // this.getBrandList();
  },
  methods: {
    getRoleList() {
      const data = {}
      postAction(`${this.patt}/role/list`, data).then((data) => {
        if (data.code == 200) {
          this.roleList = data.data.records
          this.roleList.map((item) => {
            if (item.name == this.accountInfo.roleName) {
              this.defaultCheckedId.push(item.id)
            }
          })
        } else {
          this.$message.warning(data.msg)
        }
        this.loadingRole = false
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.loadData()
    },
    beforeSubmit(e) {
      e.preventDefault()
      this.submit()
    },
    reset() {
      this.form.resetFields()
      this.$emit('close')
    },
    getQueryParams() {
      const params = this.form.getFieldsValue()
      return {
        ...params,
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      console.log(this.selectedRows)
    },
    // selectChange(selectedKey, selectedRow) {
    //   this.selectedKey = selectedKey
    //   this.selectedRow = selectedRow
    //   console.log(this.selectedRow)
    // },

    loadData() {
      var data = this.getQueryParams()
      if (this.brand) {
        data.brand = this.brand
      }
      postAction(`${this.patt}${this.urlKey}/employee/search`, data).then((data) => {
        if (data.code == 200) {
          this.dataList = data.data
          this.form.resetFields()
        } else {
          this.$message.warning(data.msg)
        }
        this.loading = false
      })
    },
    selectBrand(brand) {
      this.brand = brand
    },
    selectPermiss(permiss) {
      this.permiss = permiss
    },
    submit() {
      console.log(111);
      if (this.permiss) {
        this.permiss.map((item) => {
          if (item == '主推') {
            this.mainDesigner = 1
          }
          if (item == '选款') {
            this.chooseStyle = 1
          }
          if (item == '删款') {
            this.deleteStyle = 1
          }
        })
      } 
      if (this.showTable && this.selectedRows.length == 0) {
        this.$message.warning('请选择账号的用户！')
      } else if (this.showTable && this.selectedRow.length == 0) {
        this.$message.warning('请选择账号的角色！')
      } else {
        const params = {
          accountId: this.accountInfo.id,
          brands: this.brand,
          name: this.showTable ? this.selectedRows[0].name : this.accountInfo.name,
          account: this.showTable ? this.selectedRows[0].email : this.accountInfo.account,
          jobNumber: this.showTable ? this.selectedRows[0].jobNumber : this.accountInfo.jobNumber,
          password: this.showTable ? this.selectedRows[0].jobNumber : this.accountInfo.jobNumber,
          mobile: this.showTable ? this.selectedRows[0].mobile : this.accountInfo.mobile,
          roleId: this.ifChange ? this.selectedRow[0].id : this.defaultCheckedId[0],
          chooseStyle: this.chooseStyle ? this.chooseStyle : 0,
          deleteStyle: this.deleteStyle ? this.deleteStyle : 0,
          mainDesigner: this.mainDesigner ? this.mainDesigner : 0,
        }
        const api = this.showTable ? `${this.patt}/account/save` : `${this.patt}/account/update`
        this.$http({
          url: api,
          method: 'post',
          data: params,
        }).then((data) => {
          if (data.code == 200) {
            this.$message.success(this.showTable ? '新建帐号成功！' : '修改成功！')
            this.reset()
          } else {
            this.$message.warning(data.msg)
          }
        })
      }
    },
  },
}
</script>

<style scoped lang="less">
.main {
  // display: flex;
}
.info-action {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: flex-end;
  // margin-bottom: 20px;
}
.ml-20 {
  margin-left: 20px;
}
</style>
